package demo.util;

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageCrop {

	private final static double LENGTH = 300.0;
	private final static double AVATAR_SIZE = 180;
	
	
//	坐标xy，剪裁长宽wh，上传原始文件名file
	public static String doCrop(int x, int y, int w, int h, String rawavatar) {
		
		System.out.println(x+", "+y+", "+w+", "+h+", "+rawavatar);

//		读取上传的原始头像
		BufferedImage rawimage = null;
		try {
			rawimage = ImageIO.read(new File(rawavatar));
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		
		double width = rawimage.getWidth();
		double height = rawimage.getHeight();
//System.out.println("width:" + width + ", height:" + height);
		
		double longside = (width>height)?width:height;
//System.out.println("longside:" + longside);

		if(longside>LENGTH) {
//System.out.println("---------->" + longside/LENGTH);
			w *= (longside/LENGTH);
			h *= (longside/LENGTH);
			
			x *= (longside/LENGTH);
			y *= (longside/LENGTH);
		}
//System.out.println(x+", "+y+", "+w+", "+h);
		w = (int) ((x+w>width)?(width-x):w);
		h = (int) ((y+h>height)?(height-y):h);
//System.out.println(x+", "+y+", "+w+", "+h);
		
//		剪裁生成新头像
		BufferedImage croppedimage = rawimage.getSubimage(x, y, w, h);//subString
		
//		缩放
//		生成处理后的图片存储空间。  
        BufferedImage changedImage = new BufferedImage((int)AVATAR_SIZE, (int)AVATAR_SIZE, BufferedImage.TYPE_3BYTE_BGR);  
  
//      缩放比例。  
        double widthBo = AVATAR_SIZE/w;  
        double heightBo = AVATAR_SIZE/h;  
//System.out.println(widthBo);
        AffineTransform transform = new AffineTransform();  
        transform.setToScale(widthBo, heightBo);  
  
//      根据剪裁后的图片生成缩放后的图片
        AffineTransformOp ato = new AffineTransformOp(transform, null);  
        ato.filter(croppedimage, changedImage);  

//		取得上传文件扩展名
		String extname = "";
		if (rawavatar.lastIndexOf(".") >= 0) {
			extname = rawavatar.substring(rawavatar.lastIndexOf("."));
		}

//		保存新头像到avatar目录
		String savePath = "C:/www/JEE_WEIBO_Demo/avatar/";
		String newavatar = Long.toString(System.nanoTime()) +extname;
		try {
			ImageIO.write(changedImage, "jpg", new File(savePath + newavatar));
		} catch (IOException e) {
			e.printStackTrace();
		} 
		return newavatar;
//		
	}

}